package com.ruoyi.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.business.entity.YytMember;
import com.ruoyi.common.business.service.YytMemberService;
import com.ruoyi.common.vip.entity.YytVipMember;
import com.ruoyi.common.vip.service.YytVipMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class VipEndTimeOutTask {

    @Autowired
    private YytMemberService yytMemberService;

    @Autowired
    private YytVipMemberService yytVipMemberService;

    private static VipEndTimeOutTask task;


    @PostConstruct
    public void init() {
        task = this;
        task.yytMemberService = this.yytMemberService;
        task.yytVipMemberService = this.yytVipMemberService;
    }


    /**
     * 每天凌晨1点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void scheduledTask(){

        QueryWrapper<YytMember> wrapper = new QueryWrapper<>();
        wrapper.eq("is_vip", "1");
        List<YytMember> yytMembers = task.yytMemberService.list(wrapper);
        // 获取当前时间搓
        long time = new Date().getTime();
        for (YytMember ym : yytMembers) {
            long vipEndTime = ym.getVipEndTime().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
            if (time > vipEndTime){
                UpdateWrapper<YytMember> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", ym.getId()).set("is_vip", "0").set("vip_end_time", null);
                task.yytMemberService.update(updateWrapper);
                UpdateWrapper<YytVipMember> updateWrapper1 = new UpdateWrapper<>();
                updateWrapper1.eq("member_id", ym.getId()).eq("vip_end_time", ym.getVipEndTime()).set("status", "0");
                task.yytVipMemberService.update(updateWrapper1);
                log.info("该会员身份已过期：{}", ym.getNickname());
            }
        }

    }


}
